package top.went.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.ProductDao;
import top.went.db.dao.ProductFormatterDao;
import top.went.db.mapper.ProductMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.ProductCategoryEntity;
import top.went.pojo.ProductEntity;
import top.went.pojo.ProductFormatEntity;
import top.went.pojo.WhNumberEntity;
import top.went.vo.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 产品服务
 * 产品信息管理
 * 产品规格管理
 */
@Service
@Transactional(value = "transactionManager",rollbackFor = ServiceException.class)
public class ProductService {

    /** 产品dao*/
    private final ProductDao dao;
    private final ProductMapper productMapper;
    /** 产品规格*/
    private final ProductFormatterDao formatterDao;
    /** 产品类别*/
    private final ProductCategoryService categoryService;


    private static final Map<String,String> map = new HashMap<>();


    static {
        map.put("productEntity.productName","product_name");
        map.put("pfPrice","pf_price");
        map.put("pfMax","pf_max");
        map.put("pfMin","pf_min");
        map.put("pfCost","pf_cost");
        map.put("number","number");
    }

    @Autowired
    public ProductService(ProductDao dao, ProductMapper productMapper, ProductFormatterDao formatterDao,
                          ProductCategoryService categoryService) {
        this.dao = dao;
        this.productMapper = productMapper;
        this.formatterDao = formatterDao;
        this.categoryService = categoryService;
    }

    /**
     * 新建产品或者产品子规格
     * @param productFormatEntity
     * @param type
     * @return
     * @throws NotFoundException
     */
    public ProductFormatEntity addProduct(ProductFormatEntity productFormatEntity,boolean type)
            throws NotFoundException, ServiceException {
        ProductEntity productEntity = productFormatEntity.getTbProductByProductId();
        if (!type && productEntity.getProductId() == null){
            ProductCategoryEntity categoryEntity = productEntity.getTbProductCategoryByPcId();
            if (categoryEntity.getPcId() != null)
                  categoryEntity= categoryService.load(
                          productEntity.getTbProductCategoryByPcId().getPcId());
            else categoryEntity = null;
            productEntity.setTbProductCategoryByPcId(categoryEntity);
            productFormatEntity.setPfName("基准");
            productFormatEntity.setPfUnitCal(1L);
            productEntity.setLogicDelete(false);
        }else if (type && productEntity.getProductId() != null){
            if (formatterDao.findFormatterName(false,productFormatEntity.getPfName()) >0)
                throw new ServiceException("该规格已经存在");
            ProductEntity product = loadProduct(productEntity.getProductId().longValue());
            productFormatEntity.setTbProductByProductId(product);
            productFormatEntity.setBase(true);
        }
        productFormatEntity.setLogicDelete(false);
        try {
            if (!type)
                productFormatEntity.setTbProductByProductId(dao.save(productEntity));
            return formatterDao.save(productFormatEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("新建产品或者产品子规格失败");
        }
    }

    /**
     * 删除子规格，如果子规格是基准规格并且产品下面只有基准规格，则直接删除产品
     * @param id
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteProduct(Integer id) throws NotFoundException, ServiceException {
        boolean all = false;
        ProductFormatEntity formatEntity = load(id);
        if (!formatEntity.isBase() ){
            Long number = formatterDao.countProductFormat(formatEntity.getTbProductByProductId().getProductId());
            if (number-1 > 0 )
                throw new ServiceException("产品"+formatEntity.getTbProductByProductId().getProductName()+"有其他"+(number-1)+"个规格，无法删除");
            else
                all = true;
        }
        List<WhNumberEntity> numberEntities = (List<WhNumberEntity>) formatEntity.getTbWhNumbersByPfId();
        for (WhNumberEntity numberEntity : numberEntities) {
            if (numberEntity.getWnNumber() > 0)
                throw new ServiceException("该产品存在库存，无法删除");
        }
        try {
            formatEntity.setLogicDelete(true);
            if (all)
                formatEntity.getTbProductByProductId().setLogicDelete(true);
            formatterDao.save(formatEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("删除产品失败");
        }
        return true;
    }

    /**
     * 修改产品信息
     * @param formatEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean modifyProduct(ProductFormatEntity formatEntity,boolean base) throws NotFoundException, ServiceException {
        ProductFormatEntity productFormatEntity = load(formatEntity.getPfId());
        if (!productFormatEntity.isBase() && base)
            throw new NotFoundException("只能更改产品，不能更改规格");
        if (productFormatEntity.isBase() && !base)
            throw new NotFoundException("只能更改规格，不能更改产品");
        ProductEntity product = productFormatEntity.getTbProductByProductId();
        ProductEntity p = formatEntity.getTbProductByProductId();
        if (!productFormatEntity.isBase()) {
            modifyBase(product, p);
        }else
            productFormatEntity.setPfName(formatEntity.getPfName());
        modifyData(formatEntity, productFormatEntity);
        try {
            formatterDao.save(productFormatEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("修改产品信息失败");
        }
        return true;
    }

    /**
     * 更改基准
     * @param product
     * @param p
     * @throws NotFoundException
     */
    private void modifyBase(ProductEntity product, ProductEntity p) throws NotFoundException {
        product.setProductName(p.getProductName());
        product.setProductModel(p.getProductModel());
        ProductCategoryEntity categoryEntity = null;
        if (p.getTbProductCategoryByPcId() != null && p.getTbProductCategoryByPcId().getPcId() != null)
            categoryEntity = categoryService.load(p.getTbProductCategoryByPcId().getPcId());
        product.setTbProductCategoryByPcId(categoryEntity);
        product.setProductStock(p.getProductStock() == null ? Boolean.TRUE : p.getProductStock());
    }


    /**
     * 更改记录
     * @param formatEntity
     * @param productFormatEntity
     */
    private void modifyData(ProductFormatEntity formatEntity, ProductFormatEntity productFormatEntity) {
        productFormatEntity.setPfStatus(formatEntity.getPfStatus()==null?Boolean.TRUE:formatEntity.getPfStatus());
        productFormatEntity.setPfUnit(formatEntity.getPfUnit());
        productFormatEntity.setPfPrice(formatEntity.getPfPrice());
        productFormatEntity.setPfCost(formatEntity.getPfCost());
        productFormatEntity.setPfWeight(formatEntity.getPfWeight());
        productFormatEntity.setPfWeigtUnit(formatEntity.getPfWeigtUnit());
        productFormatEntity.setPfMin(formatEntity.getPfMin());
        productFormatEntity.setPfMax(formatEntity.getPfMax());
        productFormatEntity.setPfOther(formatEntity.getPfOther());
        productFormatEntity.setPfImf(formatEntity.getPfImf());
        productFormatEntity.setPfDate(formatEntity.getPfDate());
        productFormatEntity.setPfExpiry(formatEntity.getPfExpiry());
        productFormatEntity.setPfApprovalNumber(formatEntity.getPfApprovalNumber());
        productFormatEntity.setPfManufacturer(formatEntity.getPfManufacturer());
        productFormatEntity.setPfBatch(formatEntity.getPfBatch());
        System.out.println(formatEntity.getPfName());
    }

    /**
     * 加载产品规格信息
     * @param id
     * @return
     * @throws NotFoundException
     */
    public ProductFormatEntity load(Integer id) throws NotFoundException {
        ProductFormatEntity formatEntity= formatterDao.findByLogicDeleteAndPfId(false, id.intValue());
        if (formatEntity == null)
            throw new NotFoundException("该产品规格不存在");
        return formatEntity;
    }

    /**
     * 加载产品的所有规格
     * @param id
     * @return
     * @throws NotFoundException
     */
    public List<Product> loadFormatters(Long id) throws NotFoundException {
        ProductEntity productEntity = loadProduct(id);
        return productMapper.loadFormatter(productEntity.getProductId().longValue());
    }

    /**
     * 加载产品类别树
     * @return
     */
    public List<ProductTree> findAllProduct(){
        ProductTree tree = new ProductTree(categoryService.loadListAndProduct());
        ProductTree n = new ProductTree("无类别",formatterDao.findCategoryNull(false),-10L);
        List<ProductTree> trees=new ArrayList<>();
        trees.add(tree);
        if (n.getNodes() != null && n.getNodes().size() >0)
            trees.add(n);
        return trees;
    }

    /**
     * 加载产品信息
     * @param
     * @return
     * @throws NotFoundException
     */
    public Product load(Long id) throws NotFoundException {
        Product product = productMapper.load(id);
        if (product == null)
            throw new NotFoundException("改产品规格不存在");
        return product;
    }

    /**
     * 高级查询
     * @param search
     * @return
     */
    public PageEntity<Product> findAll(ProductSearch search) {
        if (search == null)
            return new PageEntity<Product>(0L,null);
        String order = search.getPage().getSort(map);
        if (order.length() <=0)
            order = "pf_id desc";
        Page<Product> page1 = PageHelper.startPage(search.getPage().getPage(),search.getPage().getSize(),
                "pf_status asc,"+order);
        productMapper.findAllSeniorSearch(search);
        System.out.println(page1);
        return new PageEntity<>(page1.getTotal(), page1.getResult());
    }

    /**
     * 获取订单中没有交付的产品
     * @param id
     * @return
     */
    public List<NotDetailVo> getNotDetails(Long id){
        return null;
    }

    /**
     * 加载产品
     * @return
     * @throws NotFoundException
     */
    private ProductEntity loadProduct(Long id) throws NotFoundException {
        ProductEntity product = dao.findByLogicDeleteAndProductId(false,id.intValue());
        if (product == null)
            throw new NotFoundException("产品不存在");
        return product;
    }

    /**
     * 批量删除产品
     * @param ids
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteProductAll(Long[] ids) throws NotFoundException, ServiceException {
        for (int i = 0;i < ids.length; i++){
            deleteProduct(ids[i].intValue());
        }
        return true;
    }
}
